<template>
  <div class="address-content" 
  >
    <!-- 添加地址 -->
    <el-button type="primary" @click="addNewAddress" style="margin-bottom: 20px;">新增地址</el-button>
    <!-- 收货地址表格区域 -->
    <el-table :data="addressData" border style="width: 100%" 
      highlight-current-row 
      v-loading="loading"
      element-loading-background="rgba(255, 255,255, 0.5)"
      element-loading-spinner="el-icon-loading"
      :header-cell-style="{backgroundColor:'#27ba9b',color:'#fff'}"
      @current-change="currentChange"
    >
      <el-table-column prop="receiver" label="收货人" width="80" />
      <el-table-column prop="fullLocation" label="所在地区" width="250" />
      <el-table-column prop="address" label="详细地址" width="250" />
      <el-table-column prop="postalCode" label="邮编" width="100" />
      <el-table-column prop="contact" label="电话/手机" width="160" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click=editAddress(scope.row)>修改</el-button>
          <el-popconfirm title="确认删除么？" confirm-button-text="确认" cancel-button-text="取消" @confirm="delAddress(scope.row)">
            <template #reference>
              <el-button link type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 地址弹框区域 -->
  <YDialog 
    ref="refYDialog"
    :addressForm="addressForm"
    @get-address="getAddress"
  >
  </YDialog>
</template>

<script setup>
import {ref, onMounted, nextTick } from 'vue'
import { _getAddress, _addAddress ,_editAddress, _delAddress } from '@/apis/address'
import YDialog from '@/components/YDialog/index.vue'
// Loading加载
const loading = ref(true)
// 获取弹框DOM
const refYDialog = ref(null)
// 添加地址数据对象
const addressForm = ref({
  id:'', //地址id
  addressOptions: [], //地址信息
  provinceCode:'', //省级编码
  cityCode:'', //市级/区编码
  countyCode:'', //地区编码
  address:'', //详细地址
  postalCode:'',//邮政编码
  receiver:'', //收货人姓名
  contact:'', //手机/电话
  addressTags:[], //地址标签
  isDefault: false, //是否为默认地址：0是、1否
  fullLocation:'', //收货人完整地址
})
// 重置新增地址按钮方法
const addNewAddress = () => {
  refYDialog.value.addNewAddress()
}

// 获取地址
const addressData = ref([])
const getAddress = async () => {
  const {data:res} = await _getAddress()
  addressData.value = res.result
  loading.value = false
}
onMounted(()=>{
  getAddress()
})
// 修改地址方法
const editAddress = (data) => {
  addressForm.value = {...data}
  nextTick(()=>{
    refYDialog.value.editAddress()
  })
}
// 删除地址方法
const delAddress = async (row) => {
  if (addressData.value.length === 1) {
    return ElMessage.warning('最后一条数据不能删除')
  }
  await _delAddress(row.id)
  ElMessage.success('删除成功')
  await getAddress()
}
// 选中当前行触发事件
const currentChange = (row) => {
  // console.log(row);
}
</script>

<style lang="scss" scoped>
.address-content {
  padding: 20px;
}
</style>